package com.qf.course.web.controller;

import com.qf.course.core.entity.User;
import com.qf.course.core.service.UserService;
import com.qf.course.core.util.Codes;
import com.qf.course.core.util.PinyinUtils;
import com.qf.course.core.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://10.36.135.10:8848", allowCredentials = "true")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/insert")
    public R<String> insert(User user){
        System.out.println("注册账户信息：" + user);
        user = userService.insert(user);
        return R.create("succ");
    }

    /**
     * 登录的接口
     * @return
     */
    @RequestMapping("/login")
    public R login(String username, String password, Integer role, HttpSession session){
        User user = userService.login(username, password, role);
        if (user == null) {
            return R.createFail(Codes.LOGIN_FAIL);
        }

        user.setPassword(null);
        user.setDelFlag(null);
        user.setCreateTime(null);
        user.setUpdateTime(null);
        user.setStatus(0);
        //登录成功
        session.setAttribute("login_user", user);
        return R.create(user);
    }

    /**
     * 注销当前登录的账户信息
     * @return
     */
    @RequestMapping("/logout")
    public R logout(HttpSession session){
//        session.removeAttribute("login_user");
        User user = (User) session.getAttribute("login_user");
        System.out.println("注销前，获取登录的用户信息：" + user);
        return R.create(null);
    }

    /**
     * 姓名转换成拼音的接口
     * @return
     */
    @RequestMapping("/name2pinyin")
    public R name2Pinyin(String name){
        String pinyin = PinyinUtils.str2pinyin(name);
        return R.create(pinyin);
    }
}
